import 'package:flutter/foundation.dart';
import 'package:dart_date/dart_date.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

import '../../../data/models/bt_user_info.dart';
import '../../../part/bt_rc_im_engine.dart';
import '../../utils/bt_event_bus.dart';
import '../repository/bt_message_repository.dart';
import '../utils/bt_constants.dart';
import 'bt_im_conversation.dart';

class BtConversationListModel extends ChangeNotifier {
  final int _pageSize = 30;

  final PagingController<int, BtImConversation> _pagingController = PagingController(firstPageKey: 0);

  PagingController<int, BtImConversation> get pagingController => _pagingController;

  late PageRequestListener<int> _listener;

  late final BtMessageRepository repository;

  final BtRcImEngine imEngine = BtRcImEngine();

  BtConversationListModel() {
    repository = BtMessageRepository();
    _listener = (pageKey) {
      pageKey++;
      fetchConversations(pageKey);
    };
    _pagingController.addPageRequestListener(_listener);
    eventBus.on<BtEventFn>().listen((event) {
      if (event.refresh == freshConversationList) {
        _pagingController.refresh();
      }
    });
  }

  void deleteConversation(RCIMIWConversationType type, String targetId, String? channelId) {
    imEngine.engine?.removeConversation(type, targetId, channelId);
    List<BtImConversation> itemList = _pagingController.itemList ?? [];
    itemList.removeWhere((element) => element.targetId == targetId && element.conversationType == type);

    notifyListeners();
  }

  void fetchConversations(int pageKey) {
    IRCIMIWGetConversationsCallback? callback =
        IRCIMIWGetConversationsCallback(onSuccess: (List<RCIMIWConversation>? conversationList) async {
      try {
        List<BtImConversation> conversations = [];
        final newItems = conversationList ?? [];
        for (var item in newItems) {
          BtUserInfo? userInfo = await repository.getUserInfoById(item.targetId ?? '');
          conversations.add(BtImConversation(
            conversationType: item.conversationType,
            targetId: item.targetId ?? '',
            targetName: userInfo?.nickname ?? '',
            targetAvatarUrl: userInfo?.avatarUrl ?? '',
            messageText: _buildMessageStr(item.lastMessage) ?? '',
            operationTime: _getOptTimeStr(item.operationTime ?? 0),
            unreadCount: _getUnReadCount(item.unreadCount ?? 0),
          ));
        }
        final isLastPage = newItems.length < _pageSize;
        if (isLastPage) {
          _pagingController.appendLastPage(conversations);
        } else {
          _pagingController.appendPage(conversations, pageKey);
        }
      } catch (error) {
        _pagingController.error = error;
      }
    }, onError: (int? code) {
//...
    });
    imEngine.engine
        ?.getConversations([RCIMIWConversationType.private], null, 0, _pageSize, callback: callback);
  }

  String _getOptTimeStr(int optTime) {
    var date = DateTime.fromMillisecondsSinceEpoch(optTime);
    if (date.isToday) {
      return date.format("HH:mm");
    } else if (date.isSameYear(DateTime.now())) {
      return date.format("MM-dd HH:mm");
    } else {
      return date.format("yyyy-MM-dd");
    }
  }

  String _getUnReadCount(int unreadCount) {
    return unreadCount <= 99 ? '$unreadCount' : '99+';
  }

  String? _buildMessageStr(RCIMIWMessage? message) {
    if (message is RCIMIWTextMessage) {
      return message.text;
    } else if (message is RCIMIWVoiceMessage) {
      return '''[Voice] ${message.duration}"''';
    } else if (message is RCIMIWImageMessage) {
      return '''[Picture]''';
    } else if (message is RCIMIWFileMessage) {
      return '''[File]''';
    } else {
      return "'''[Message]'''";
    }
  }
}
